package com.fengxing.ams.web.security.utils;

import org.apache.commons.lang.StringUtils;

import com.fengxing.ams.pub.util.Encodes;

public class PasswordUtil {
	public static final String HASH_ALGORITHM = "SHA-1";
	public static final int HASH_INTERATIONS = 1024;
	private static final int SALT_SIZE = 8;
	
	/**
	 * 生成安全的密码，生成随机的16位salt并经过1024次 sha-1 hash
	 */
	public static String entryptPassword(String plainPassword) {
		byte[] salt = Digests.generateSalt(SALT_SIZE);
		byte[] hashPassword = Digests.sha1(plainPassword.getBytes(), salt, HASH_INTERATIONS);
		return Encodes.encodeHex(salt)+Encodes.encodeHex(hashPassword);
	}
	
	/**
	 * @param plainPassword
	 * @param password
	 * @return
	 */
	public static boolean validPassword(String plainPassword, String password) {
		byte[] salt = Encodes.decodeHex(password.substring(0,16));
		password = password.substring(16);
		plainPassword = Encodes.encodeHex(Digests.sha1(plainPassword.getBytes(), salt, HASH_INTERATIONS));
		return StringUtils.equals(password, plainPassword);
	}
}
